import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;

import javax.jms.BytesMessage;
import javax.jms.Connection;
import javax.jms.JMSException;
import javax.jms.MapMessage;
import javax.jms.Message;
import javax.jms.MessageListener;
import javax.jms.MessageProducer;
import javax.jms.Queue;
import javax.jms.Session;
import javax.jms.TextMessage;
import javax.jms.Topic;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.activemq.ActiveMQConnectionFactory;
import org.apache.activemq.command.ActiveMQQueue;
import org.apache.activemq.command.ActiveMQTopic;


public class StartListener extends HttpServlet {

	private static final long serialVersionUID = 1L;
	
	/**
	 * Constructor of the object.
	 */
	public StartListener() {
		super();
	}

	/**
	 * Destruction of the servlet. <br>
	 */
	public void destroy() {
		super.destroy(); // Just puts "destroy" string in log
		// Put your code here
	}

	/**
	 * The doGet method of the servlet. <br>
	 *
	 * This method is called when a form has its tag value method equals to get.
	 * 
	 * @param request the request send by the client to the server
	 * @param response the response send by the server to the client
	 * @throws ServletException if an error occurred
	 * @throws IOException if an error occurred
	 */
	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {

		response.setContentType("text/html");
		PrintWriter out = response.getWriter();
		out.println("<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\">");
		out.println("<HTML>");
		out.println("  <HEAD><TITLE>A Servlet</TITLE></HEAD>");
		out.println("  <BODY>");
		out.print("    This is ");
		out.print(this.getClass());
		out.println(", using the GET method");
		out.println("  </BODY>");
		out.println("</HTML>");
		out.flush();
		out.close();
	}

	/**
	 * The doPost method of the servlet. <br>
	 *
	 * This method is called when a form has its tag value method equals to post.
	 * 
	 * @param request the request send by the client to the server
	 * @param response the response send by the server to the client
	 * @throws ServletException if an error occurred
	 * @throws IOException if an error occurred
	 */
	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {

		response.setContentType("text/html");
		PrintWriter out = response.getWriter();
		out.println("<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\">");
		out.println("<HTML>");
		out.println("  <HEAD><TITLE>A Servlet</TITLE></HEAD>");
		out.println("  <BODY>");
		out.print("    This is ");
		out.print(this.getClass());
		out.println(", using the POST method");
		out.println("  </BODY>");
		out.println("</HTML>");
		out.flush();
		out.close();
	}

	/**
	 * Initialization of the servlet. <br>
	 *
	 * @throws ServletException if an error occurs
	 */
	public void init() throws ServletException {
		System.out.println("listenser start");
		
		//connectionFactory ->Connection->session->message
		ActiveMQConnectionFactory factory = new ActiveMQConnectionFactory("nio://192.168.1.48:61616");
		try {
			Connection connection = factory.createConnection("system","manager");
			connection.start();
			final Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
			
			/*queue*/
			Queue queue = new ActiveMQQueue("testQueue");
			
			session.createConsumer(queue).setMessageListener(new MessageListener() {
				
				@Override
				public void onMessage(Message arg0) {
					try {
						System.out.println("consumer1"+((TextMessage)arg0).getText());
						print( arg0) ;
						
						MessageProducer reply = session.createProducer(arg0.getJMSReplyTo());
						reply.send(session.createTextMessage("收到请打印"));
						
					} catch (JMSException e) {
						e.printStackTrace();
					}
					
				}
			});
			
			session.createConsumer(queue).setMessageListener(new MessageListener() {
				@Override
				public void onMessage(Message arg0) {
					try {
						System.out.println("consumer2 "+((TextMessage)arg0).getText());
					} catch (JMSException e) {
						e.printStackTrace();
					}
					
				}
				
			});
			
			
			/*topic*/
			Topic topic = new ActiveMQTopic("testTopic");
			session.createConsumer(topic).setMessageListener(new MessageListener() {
				
				@Override
				public void onMessage(Message arg0) {
					try {
						System.out.println("consumer1 "+((TextMessage)arg0).getText());
					} catch (JMSException e) {
						e.printStackTrace();
					}
					
				}
			});
			
			session.createConsumer(topic).setMessageListener(new MessageListener() {
				@Override
				public void onMessage(Message arg0) {
					try {
						System.out.println("consumer2 "+((TextMessage)arg0).getText());
						
					} catch (JMSException e) {
						e.printStackTrace();
					}
					
				}
			});
			
			
			/*mapmessage
			Queue queue = new ActiveMQQueue("testQueue");
			session.createConsumer(queue).setMessageListener(new MessageListener() {
				@Override
				public void onMessage(Message arg0) {
					try {
						System.out.println("consumer mapmessage "+((MapMessage)arg0).getInt("intmessage"));
					} catch (JMSException e) {
						e.printStackTrace();
					}
					
				}
			});
			*/
			
			/*bytemessage
			Queue queue = new ActiveMQQueue("testQueue");
			session.createConsumer(queue).setMessageListener(new MessageListener() {
				@Override
				public void onMessage(Message arg0) {
					try {
						BytesMessage k = ((BytesMessage)arg0);
						byte[] bys=new byte[(int)k.getBodyLength()];
						k.readBytes(bys);
						ArrayList<String> list = Encode.decode(bys);
						for (String string : list) {
							System.out.println("consumer BytesMessage "+string);
						}
					} catch (JMSException e) {
						e.printStackTrace();
					}
					
				}
			});
			*/
			
			/*TemporaryQueue*/
			session.createConsumer(session.createTemporaryQueue()).setMessageListener(new MessageListener() {
				@Override
				public void onMessage(Message arg0) {
					try {
						System.out.println("TemporaryQueue consumer "+((TextMessage)arg0).getText());
					} catch (JMSException e) {
						e.printStackTrace();
					}
					
				}
				
			});
			
		} catch (JMSException e) {
			e.printStackTrace();
		}
		
	}
	
	private void print(Message arg0) throws JMSException{
		//消息目的地 是topic还是queue
		System.out.println("JMSDestination "+arg0.getJMSDestination());
		//persistent或nonpersistent。前者表示消息在被消费之前，如果JMS提供者DOWN了，重新启动后消息仍然存在。后者在这种情况下表示消息会被丢失
		System.out.println("JMSDeliveryMode "+arg0.getJMSDeliveryMode());
		//表示一个消息的有效期。只有在这个有效期内，消息消费者才可以消费这个消息。默认值为0，表示消息永不过期
		System.out.println("JMSExpiration "+arg0.getJMSExpiration());
		//消息的优先级。0-4为正常的优先级，5-9为高优先级
		System.out.println("JMSPriority "+arg0.getJMSPriority());
		//消息体结构
		System.out.println("JMSType "+arg0.getJMSType());
	}

}
